<template>
    <div class="app-container">
        <U02Anim/>

        <el-container>
          <el-aside width="68%"
                    style="background-color: #8f72ba22;"
          >
              <h3> 测试链路人工审核界面 ⚙️ </h3>
          </el-aside>
          <el-main>
              <el-text>
                您好！欢迎来到链路人工审核界面。<br>
                在这里，您将是关键的“把关人”！所有需要您慧眼识别和修正的链路信息都会在此呈现。
            </el-text>
          </el-main>
        </el-container>

        <div style="margin-bottom: 1em;">
            <h4 style="color: var(--el-color-info);"> 项目列表
            </h4>
            <el-text>
                已为您收集到 <span style="color: var(--el-color-success);">{{ed.df1.size}}</span>个项目的信息， 只需点击下方的项目Tab，即可轻松管理和查看该项目下的所有链路详情。感谢您的专业与细致！
                <el-button style="margin-left:.5em" :icon="Refresh" circle @click="U.f00_getChains" />
            </el-text>
        </div>

        <el-collapse v-model="ed.p01_activeNames">
            <el-collapse-item v-for="(kv, i) in ed.df1" :name="i + 1">
                <template #title="{ isActive }"> <div>
                    项目 {{String(i).padStart(2,'0')}}:
                    <el-text
                        style="margin-left: 10px; font-weight: bold;"
                        type="primary"> {{kv[1].L[0].projectName}}: </el-text>
                    <el-text>
                        找到 <el-text type="success"> {{kv[1].q02_totalCount}} </el-text> 条链路 </el-text>
                </div> </template>
        <el-table v-loading="ed.loading" :data="kv[1].L" >
          <el-table-column prop="projectId" label="项目ID" width="180" />
          <el-table-column prop="cid" label="链路ID" width="180" />
          <el-table-column prop="projectName" label="项目名称" width="200" />
          <!-- <el-table-column prop="creatorD" label="作者" width="200" />  🦜: token should not be visible-->
          <el-table-column prop="createdAtD" label="创作时间" width="200" />
          <!-- <el-table-column label="创作时间" width="200" >
               <template #default="scope">
               <div style="display: flex; align-items: center">
               <el-icon><timer /></el-icon>
               <span style="margin-left: 10px">{{ scope.row.createdAtD }}</span>
               </div>
               </template>
               </el-table-column> -->
          <el-table-column prop="N" label="链路长度" width="100" />
          <el-table-column label="状态" >
              <template #default="scope">
                  <span class="blink" style="display: inline-flex; align-items: center; margin-right: 10px;">
                      <svg width="10" height="10" xmlns="http://www.w3.org/2000/svg"> <circle cx="5" cy="5" r="4" :fill="scope.row.colorD" /> </svg>
                  </span>
                  <el-text v-if="scope.row.paused" class="blink" type="info">{{ scope.row.statusD }} </el-text>
                  <el-text v-else class="blink" type="success">{{ scope.row.statusD }} </el-text>
                  <!-- <span class="blink" style="margin-left: 10px">{{ scope.row.statusD }}</span> -->
              </template>
          </el-table-column>

          <el-table-column fixed="right" label="Operations" min-width="120">
              <template #default="scope">
                  <el-button link type="primary" size="small" @click="U.edit(scope.row)"> Edit </el-button>
                  <el-button link  v-if="scope.row.paused" size="small" @click="U.resume(scope.row)"> Resume </el-button>
                  <el-button link  v-else size="small" @click="U.pause(scope.row)"> Pause </el-button>
                    <!-- <el-button link type="primary" size="small" @click="handleClick"> Detail </el-button> -->
            </template>
        </el-table-column>
      </el-table>
      <pagination v-show="ed.q02_totalCount>0" :total="kv[1].q02_totalCount" v-model:page="kv[1].q01_pageIdx" v-model:limit="kv[1].q03_pageSize" @pagination="U.f00_getChains" />
      </el-collapse-item>
    </el-collapse>
    <!-- <el-table v-loading="ed.loading" :data="ed.df" > -->
    </div>
</template>

<script setup lang="ts">
 import { watch, ref, onMounted, markRaw, reactive} from 'vue';
 import { Refresh, Search, Edit, CaretRight,Timer, Download, Calendar } from '@element-plus/icons-vue';
 import { parseTime } from '@/utils';
 import useUserStore from '@/store/modules/user'
 import U02Anim from '@/components/U02Anim.vue';
 import { useRouter } from 'vue-router';
 const U1 = useUserStore();
 import { U2 } from '@/utils/u';

 import {pageIt, PG2, TestChainInfo, W, r01newTestProject,
         r02getChainInfos, r03pauseChain, r04resumeChain, r05getChainById,
 } from '@/api/hi_api';

 interface P1{
    L0:TestChainInfo[], 
      L: TestChainInfo[],
     q01_pageIdx: number, // 🦜 : 1-based
     q02_totalCount: number,
     q03_pageSize: number
 }

 const ed = reactive({
     q02_totalCount: 0,
     q01_pageIdx: 1,// 🦜 : 1-based
     q03_pageSize: 0xffff,

     loading: false,
     now: new Date(),
     df: [] as TestChainInfo[], //  the table data for manipulating
     df1: new Map<string, P1>(), // the grouped table data

     p01_activeNames: ['1'],
 });
 const router = useRouter();

 onMounted(async () => {
     U.start_loading(`Loading chain infos:...`);
     try {
         await U.f00_getChains()// 🦜 : they will throw errors as needed
     } finally {
         U.stop_loading();
     }
 });
 class U{
     static start_loading(s: string = "Loading") {ed.loading = U2.start_loading(s);}
     static stop_loading() {ed.loading = U2.stop_loading();}
     static resume = async (row: TestChainInfo) => {
         // Resume the chain
         let cid = row.cid;
         U.start_loading(`Resuming chain: ${cid}...`);
         if (cid) {
             try {
                 await r04resumeChain(cid);
                 row.ct *= -1;// 🦜 : modify it locally
             } catch (e) {
                 console.error('Failed to resume chain', e);
             }
         }
         U.stop_loading();
     };
     static pause = async (row: TestChainInfo) => {
         // Pause the chain
         let cid = row.cid;
         U.start_loading(`Pausing chain: ${cid}...`);
         if (cid) {
             try {
                 await r03pauseChain(cid);
                 row.ct *= -1;// 🦜 : modify it locally
             } catch (e) {
                 console.error('Failed to pause chain', e);
             }
         } else {
             console.error('Invalid row data for pausing', row);
         }
         U.stop_loading();
     };
     static edit = (row: TestChainInfo) => {
         console.log("Editing row: ", row);
         // Navigate to the edit page with the cid
         if (row && row.cid) {
             router.push({ name: 'chain-edit', params: { cid: row.cid } });
         } else {
             console.error('Invalid row data for editing', row);
         }
     };
     static f00_getChains = async () => {
         // Fetch TestChainInfo list
         try {
             ed.loading = true;
             const res = await r02getChainInfos(true, ed);
             // type ED2<T> = [T[], number, number]; // (current page items, total items, total pages)
             if (res.ok() && Array.isArray(res.data.l)) {
                 // ✅️ fetched
                 ed.df = res.data.l
                 U.f01_updateDf1(ed.df);
                 ed.q02_totalCount = res.data.q02_totalCount;
             } else {
                 console.error('Unexpected response format', res);
             }
             ed.loading = false;
         } catch (e) {
             console.error('Failed to fetch chains', e);
         }
     };

     static f01_updateDf1 = (df: TestChainInfo[]): Map<string, P1> => {
         // Group by projectId
         // 0. clear df1, but keep the page info
         // const df1 = new Map<string, P1>();
         let df1 = ed.df1;// reference to the existing df1
         for (const i of ed.df1.keys()) {
             ed.df1.get(i)!.L0 = [];
             ed.df1.get(i)!.L = [];
             ed.df1.get(i)!.q02_totalCount = 0;
         }
         // 1. group by projectId
         df.forEach((i) => {
             if (!df1.has(i.projectId)) {
                 df1.set(i.projectId, {
                     L: [],
                     L0: [],
                     q01_pageIdx: 1,
                     q02_totalCount: 0,
                     q03_pageSize: 5
                 });
             }
             const p1 = df1.get(i.projectId)!;
             p1.L.push(i);
             p1.q02_totalCount++;
         });
         // 3. remove the empty projects and page the rest
         df1.forEach((v, k) => {
             if (v.L.length === 0) {
                 df1.delete(k);
             }else{
                 let o : PG2<TestChainInfo> = pageIt<TestChainInfo>( v.L, v.q03_pageSize, v.q01_pageIdx);
                 v.L = o.l;
                 v.q02_totalCount = o.q02_totalCount;
             }
         });
         // 4. page each project 
         return df1;
     };
 };

</script>

<style lang="scss">
 @use 'base';

 .icon-ele {
     margin: 0 8px 0 auto;
     color: #409eff;
}
</style>
